<?php
/**
 * Created by PhpStorm.
 * User: 96151
 * Date: 2018/12/28
 * Time: 12:49
 */

/**
 * 神策接口
 * Class SensorsDataApiService
 */
namespace app\common\service;
class SensorsDataApiService
{

    public static  $token = "1c5821226bef885042c09a4d82fb3c1fe372b8aca1cdd8450074959919a6d2bc";

    public static  $project = "production";

    public function __construct()
    {
        if ( ENV == "test" ){
            self::$project = "default";
            self::$token = "02823d748fba7ceec03717d7eb9793217f9b99729813e212ae66276cf1809afe";
        }
    }

    /**
     * 获取文章点击展示数据
     * @param string $start_time
     * @param string $end_time
     * @return array
     */
    public function  get_app_article_click_display_data( $start_time = "", $end_time = "" )
    {
        $url = "https://hold.cloud.sensorsdata.cn/api/sql/query/";
        $start_time = $start_time ?: date( 'Y-m-d H:i:00', time() - 120 );
        $end_time = $end_time ?: date( 'Y-m-d H:i:59', time() - 120 );
        $sql = "select articleid,userid,time,is_login,".'$os'.",client_sn,operationtype from events where event = 'articleOperation' and `time` between '{$start_time}' and '{$end_time}' and screenid = 'Feed' order by `time` desc";
        $data = $this->send_sql( $url, $sql );
        $data  = $data ?: array();

        $data_list = array();

        if ( $data ){
            $data = trim( $data, "\n");
            $post_json_list = explode( "\n", $data );
            foreach ( $post_json_list as $value ){
                $info = json_decode( $value , true);
                $info['$os'] = strtolower( $info['$os'] );
                $data_list[] = $info;
            }
        }
        return $data_list;
    }

    /**
     * 发送查询数据获取结果
     * @param $url
     * @param $sql
     * @return bool|mixed
     */
    public function send_sql( $url, $sql )
    {
        if ( !$sql ){
            return false;
        }

        $param = array(
            "q" => $sql,
            "format" => "json",
            "project" => self::$project,
            "token"   => self::$token
        );

        $HttpRequestService = new HttpRequestService();
        $data = $HttpRequestService->HttpGet( $url, $param )->GetResponseOriBody();
        return $data;
    }


}